<template>
  <view class="container">
    <view class="scrollable-content">
    <!-- 学生视图 -->
    <view v-if="isStudentView">
      <Card class="practice-card" :shadow="false">
        <view class="card-header">
          <text class="card-title">今日计划</text>
        </view>
        <swiper class="practice-swiper" :indicator-dots="false" :autoplay="false" :interval="5000" :duration="300" circular>
          <swiper-item>
            <view class="practice-item item-word" @click="onWordFastClick">
              <view class="practice-icon">📘</view>
              <view class="practice-title">单词速记</view>
              <view class="practice-desc">为你推荐日常沟通必备、零基础入门、四级词汇…</view>
              <view class="action-btn">选词书</view>
            </view>
          </swiper-item>
          <swiper-item>
            <view class="practice-item item-reading" @click="onMorningReadingClick">
              <view class="practice-icon">⏰</view>
              <view class="practice-title">每日晨读</view>
              <view class="practice-desc">She works at a restaurant in the touri…</view>
              <view class="action-btn">去晨读</view>
            </view>
          </swiper-item>
        </swiper>
      </Card>
      <view class="modules">
        <view class="module-row">
          <Card class="module-card" clickable @click="goToGoals">
            <view class="module-icon goal-icon">🎯</view>
            <text class="module-title">我的目标</text>
          </Card>
          <Card class="module-card" clickable @click="goToPlans">
            <view class="module-icon plan-icon">📝</view>
            <text class="module-title">学习计划</text>
          </Card>
        </view>
        <view class="module-row">
          <Card class="module-card" clickable @click="goToWishPool">
            <view class="module-icon wish-icon">🎁</view>
            <text class="module-title">许愿池</text>
          </Card>
        </view>
      </view>
    </view>

    <!-- 家长/默认视图 -->
    <view v-else>
      <!-- 顶部欢迎卡片 -->
      <view class="welcome-card">
        <text class="welcome-title">欢迎回来，{{ displayName }}</text>
        
        <!-- 关键数据统计 -->
        <view class="stats-container">
          <view class="stat-item">
            <text class="stat-icon">⭐</text>
            <text class="stat-value">{{ points }}</text>
            <text class="stat-label">积分余额</text>
          </view>
          <view class="stat-item">
            <text class="stat-icon">🚩</text>
            <text class="stat-value">{{ activeGoals }}</text>
            <text class="stat-label">进行中目标</text>
          </view>
          <view class="stat-item">
            <text class="stat-icon">⏱️</text>
            <text class="stat-value">{{ todaysTasks }}</text>
            <text class="stat-label">今日待办</text>
          </view>
        </view>
      </view>
      
      <!-- 我的目标 -->
      <view class="section">
        <view class="section-header">
          <text class="section-title">我的目标</text>
          <text class="section-more" @click="goToAllGoals">查看所有 →</text>
        </view>
        
        <!-- 目标卡片 -->
        <Card class="goal-card" v-for="goal in displayGoals" :key="goal.id" hover-class="card-hover" :clickable="true">
          <view @click="goToGoalDetail(goal)" class="goal-card-content">
          <view class="goal-header">
            <text class="goal-title">{{ goal.title }}</text>
            <text class="goal-type" :class="goal.typeClass">{{ goal.type }}</text>
          </view>
          <text class="goal-desc">{{ goal.description }}</text>
          <view class="goal-progress-section">
            <view class="progress-label">
              <text>进度</text>
              <text class="progress-percentage">{{ goal.progress }}%</text>
            </view>
            <view class="progress-bar">
              <view class="progress-fill" :style="{ width: goal.progress + '%' }"></view>
            </view>
          </view>
          <view class="goal-footer">
            <text class="goal-deadline">截止日期: {{ goal.deadline }}</text>
            <text class="goal-status">{{ goal.status }}</text>
          </view>
          </view>
        </Card>
        
        <!-- 当剩余目标大于0时显示更多提示卡片 -->
        <Card v-if="remainingGoals > 0" class="more-goals-card" hover-class="card-hover">
          <view class="more-goals-content" @click="goToAllGoals">
            <text class="more-goals-icon">📋</text>
            <text class="more-goals-text">还有 {{ remainingGoals }} 个目标，点击查看全部</text>
            <text class="more-goals-arrow">→</text>
          </view>
        </Card>
      </view>
      
      <!-- 每日计划看板 -->
      <view class="section">
        <view class="section-header">
          <text class="section-title">每日计划看板</text>
          <text class="current-date">{{ currentDate }}</text>
        </view>
        
        <!-- 计划列表 -->
        <view class="plan-list">
          <Card class="plan-card" v-for="plan in plans" :key="plan.id" hover-class="card-hover">
            <view class="plan-header">
              <text class="plan-title">{{ plan.title }}</text>
              <text class="plan-status" :class="plan.statusClass">{{ plan.status }}</text>
            </view>
            <text class="plan-time">{{ plan.time }}</text>
          </Card>
        </view>
      </view>
    </view>
    
    </view>
  </view>
</template>

<script>
import { getStorage } from '../../utils/storage.js';
import { services } from '../../api/index.js';
const userAPI = services.user;
const goalAPI = services.goal;

export default {
  data() {
    return {
      userInfo: {
        username: '',
        nickname: '',
        avatar: ''
      },
      points: 0, // 用户积分
      activeGoals: 0, // 进行中目标数量
      todaysTasks: 0, // 今日待办数量
      currentDate: '', // 当前日期
      
      // 真实数据将通过API获取
      goals: [],
      plans: []
    };
  },
  
  computed: {
    // 计算显示的目标数量（最多4个）
    displayGoals() {
      return this.goals.slice(0, 3);
    },
    remainingGoals() {
      const shown = 3;
      return Math.max(0, (this.goals?.length || 0) - shown);
    },
    displayName() {
      return this.userInfo?.nickname || this.userInfo?.username || '学习者';
    },
    isStudentView() {
      const info = this.userInfo || {};
      const stored = getStorage('userInfo') || {};
      const role = info.userRole || info.user?.userRole || stored.userRole || stored.user?.userRole;
      return role === 'STUDENT';
    }
  },
  
  async onLoad() {
    await this.fetchHomeData();
  },
  onShow() {
    // 仅作为 TabBar 首页渲染，不再做跨页重定向
  },
  onPullDownRefresh() {
    this.fetchHomeData()
      .finally(() => uni.stopPullDownRefresh());
  },
  
  methods: {
    // 根据角色决定渲染内容
    isStudent() {
      const userInfo = getStorage('userInfo') || {};
      return (userInfo.userRole || userInfo.user?.userRole) === 'STUDENT';
    },
    onWordFastClick() {
      uni.showToast({ title: '即将进入单词速记', icon: 'none' });
    },
    onMorningReadingClick() {
      uni.showToast({ title: '即将进入每日晨读', icon: 'none' });
    },
    goToGoals() {
      uni.navigateTo({ url: '/pages/goal/list' });
    },
    goToPlans() {
      uni.navigateTo({ url: '/pages/plan/list' });
    },
    goToWishPool() {
      uni.navigateTo({ url: '/pages/wish/pool' });
    },
    async fetchHomeData() {
      try {
        uni.showLoading({ title: '加载中...' });
        // 获取用户信息
        const userInfo = getStorage('userInfo');
        if (userInfo) {
          this.userInfo = userInfo;
        }
        // 设置当前日期
        this.setCurrentDate();
        // 并行获取
        const [dashboardData, goalsResp, tasksData] = await Promise.all([
          userAPI.getUserDashboardData(),
          goalAPI.getGoalsList(),
          userAPI.getUserTodayTasks()
        ]);
        if (dashboardData) {
          this.points = dashboardData.points || 0;
          this.activeGoals = dashboardData.activeGoals || 0;
          this.todaysTasks = dashboardData.todaysTasks || 0;
        }
        const goalsData = goalsResp?.data || goalsResp || {};
        if (Array.isArray(goalsData.rows)) {
          this.goals = goalsData.rows.map(item => {
            const typeMap = {
              '1': { label: '学习目标', cls: 'type-learning' },
              '2': { label: '运动目标', cls: 'type-sport' },
              '3': { label: '计划目标', cls: 'type-plan' },
              1: { label: '学习目标', cls: 'type-learning' },
              2: { label: '运动目标', cls: 'type-sport' },
              3: { label: '计划目标', cls: 'type-plan' }
            };
            const statusText = item.status === 'PENDING' ? '未开始' : (item.status === 'IN_PROGRESS' ? '进行中' : '已完成');
            const t = typeMap[item.goalType] || { label: '学习目标', cls: 'type-learning' };
            return {
              id: item.id,
              title: item.title,
              description: item.description || '',
              progress: 0,
              deadline: item.deadline || '',
              status: statusText,
              type: t.label,
              typeClass: t.cls
            };
          });
        }
        if (tasksData && tasksData.tasks) {
          this.plans = tasksData.tasks.map(task => ({
            id: task.id,
            title: task.title,
            time: `${task.startTime} - ${task.endTime}`,
            status: task.status === 'in-progress' ? '进行中' : '待开始',
            statusClass: task.status === 'in-progress' ? 'status-in-progress' : 'status-pending'
          }));
        }
      } catch (error) {
        console.error('加载数据失败:', error);
        uni.showToast({ title: '加载数据失败，请稍后重试', icon: 'none' });
      } finally {
        uni.hideLoading();
      }
    },
    // 设置当前日期
    setCurrentDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1;
      const day = now.getDate();
      this.currentDate = `${year}年${month}月${day}日`;
    },
    
    goToAllGoals() {
      uni.navigateTo({
        url: '/pages/goal/list'
      });
    },
    
    // 跳转到目标详情页
    goToGoalDetail(goal) {
      // 根据目标类型跳转到不同的详情页
      if (goal.type === '学习目标') {
        uni.navigateTo({
          url: `/pages/goal/learning-detail?id=${goal.id}`
        });
      } else if (goal.type === '运动目标') {
        uni.navigateTo({
          url: `/pages/goal/life-detail?id=${goal.id}`
        });
      } else if (goal.type === '计划目标') {
        uni.navigateTo({
          url: `/pages/plan/detail?id=${goal.id}`
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>

  /* 可滚动内容区域 */
  .scrollable-content {
    flex: 1;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch; /* iOS设备上的平滑滚动 */
    padding-bottom: calc(env(safe-area-inset-bottom) + 140rpx);
  }
  
  /* 隐藏滚动条但保留滚动功能 */
  .scrollable-content::-webkit-scrollbar {
    display: none;
  }
  
  .scrollable-content {
    -ms-overflow-style: none;
    scrollbar-width: none;
  }

.container {
  padding: 0;
  background-color: $background-color;
  min-height: 100vh;
  box-sizing: border-box;
  /* 适配刘海屏等异形屏设备的顶部安全区域 */
  padding-top: env(safe-area-inset-top);
  /* 重置可能存在的默认边距 */
  margin-top: 0;
  /* 确保内容在有限空间内合理分布 */
  display: flex;
  flex-direction: column;
}

/* 移除可能的页面根元素默认样式 */
page {
  margin: 0;
  padding: 0;
  background-color: $background-color;
}

/* 欢迎卡片 */
.welcome-card {
  margin: $spacing-base;
  border-radius: 16rpx;
  padding: $spacing-base;
  background: linear-gradient(135deg, #1989fa 0%, #52c41a 100%);
  color: white;
  box-shadow: 0 4rpx 14rpx rgba(0, 0, 0, 0.08);
}

.welcome-title {
  font-size: $font-size-base;
  font-weight: bold;
  margin-bottom: $spacing-sm;
  display: block;
}

/* 统计数据 */
.stats-container {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.stat-icon {
  font-size: 40rpx;
  margin-bottom: 8rpx;
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-value {
  font-size: $font-size-lg;
  font-weight: bold;
  margin-bottom: 4rpx;
}

.stat-label {
  font-size: $font-size-xs;
  opacity: 0.9;
}

/* 通用区域样式 */
.section {
  margin: $spacing-base;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: $spacing-base;
}

.section-title {
  font-size: $font-size-base;
  font-weight: bold;
  color: $text-primary;
}

.section-more {
  font-size: $font-size-sm;
  color: $primary-color;
}

.current-date {
  font-size: $font-size-sm;
  color: $text-secondary;
}

/* 学生视图样式 */
.user-card {
  margin: $spacing-base;
}

.user-info {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  margin-right: $spacing-base;
  overflow: hidden;
  background-color: $primary-color;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-img { width: 100%; height: 100%; }
.avatar-placeholder { color: #fff; font-size: $font-size-sm; }

.user-details { flex: 1; }
.username { font-size: $font-size-lg; font-weight: bold; color: $text-primary; display: block; margin-bottom: $spacing-xs; }
.user-type { font-size: $font-size-sm; color: $text-secondary; }
.points-info { text-align: right; }
.points-label { font-size: $font-size-sm; color: $text-secondary; display: block; margin-bottom: $spacing-xs; }
.points-value { font-size: $font-size-lg; font-weight: bold; color: $primary-color; }

.practice-card { margin: $spacing-base; overflow: visible; }
.practice-swiper { height: 360rpx; }
.practice-item {
  height: 100%;
  margin: 0 $spacing-sm;
  padding: $spacing-lg $spacing-base;
  padding-bottom: 40rpx; /* 明确的底部留白，避免按钮贴边 */
  border-radius: 24rpx;
  background: #f6f7fb;
  box-shadow: 0 8rpx 24rpx rgba(0,0,0,0.06);
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  box-sizing: border-box;
}
.item-word { background: linear-gradient(135deg, #dff7ea, #e9fbef); }
.item-reading { background: linear-gradient(135deg, #e6f0ff, #edf4ff); }
.practice-icon { font-size: 56rpx; }
.practice-title { font-size: $font-size-base; font-weight: bold; color: $text-primary; }
.practice-desc { font-size: $font-size-sm; color: $text-secondary; }
.action-btn { align-self: flex-start; margin-top: 24rpx; padding: 16rpx 36rpx; background: #ffffff; color: $text-primary; border-radius: 999rpx; font-size: $font-size-sm; box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.06); }

.modules { margin: $spacing-base; margin-bottom: 120rpx; }
.module-row { display: flex; flex-direction: row; margin-bottom: $spacing-base; }
.module-card { flex: 1; margin-right: $spacing-sm; text-align: center; padding: $spacing-lg $spacing-base; }
.module-card:last-child { margin-right: 0; }
.module-icon { font-size: 60rpx; margin-bottom: $spacing-sm; }
.module-title { font-size: $font-size-sm; color: $text-primary; }

/* 目标卡片 */
.goal-card {
  margin-bottom: $spacing-base;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  background-color: white;
}

/* 目标卡片内容容器 - 确保整个卡片区域可点击 */
.goal-card-content {
  width: 100%;
  height: 100%;
  cursor: pointer;
}

/* 查看更多目标卡片 */
.more-goals-card {
  margin-bottom: $spacing-base;
  border-radius: 16rpx;
  overflow: hidden;
  border: 1rpx dashed $border-color;
  background-color: #f9f9f9;
}

.more-goals-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: $spacing-base;
  cursor: pointer;
}

.more-goals-icon {
  font-size: 48rpx;
  margin-right: $spacing-xs;
}

.more-goals-text {
  flex: 1;
  font-size: $font-size-base;
  color: $text-secondary;
  text-align: center;
}

.more-goals-arrow {
  font-size: $font-size-base;
  color: $primary-color;
  margin-left: $spacing-xs;
}

.goal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: $spacing-xs;
}

.goal-title {
  font-size: $font-size-base;
  font-weight: bold;
  color: $text-primary;
  flex: 1;
}

.goal-type {
  font-size: $font-size-xs;
  padding: 4rpx 16rpx;
  border-radius: 10rpx;
  color: #fff;
}
/* 目标类型颜色区分 */
.type-learning { background-color: #1677ff; }
.type-sport { background-color: #52c41a; }
.type-plan { background-color: #faad14; }

.goal-desc {
  font-size: $font-size-sm;
  color: $text-secondary;
  margin-bottom: $spacing-base;
  line-height: 1.4;
}

.goal-progress-section {
  margin-bottom: $spacing-base;
}

.progress-label {
  display: flex;
  justify-content: space-between;
  margin-bottom: $spacing-xs;
  font-size: $font-size-sm;
  color: $text-secondary;
}

.progress-percentage {
  font-weight: bold;
  color: $primary-color;
}

.progress-bar {
  width: 100%;
  height: 10rpx;
  background-color: #f0f0f0;
  border-radius: 5rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: $primary-color;
  border-radius: 5rpx;
  transition: width 0.3s ease;
}

.goal-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: $font-size-xs;
}

.goal-deadline {
  color: $text-secondary;
}

.goal-status {
  color: #52c41a;
  font-weight: bold;
  background-color: rgba(82, 196, 26, 0.1);
  padding: 4rpx 16rpx;
  border-radius: 10rpx;
}

/* 计划列表 */
.plan-list {
  margin-bottom: $spacing-xl;
}

.plan-card {
  margin-bottom: $spacing-base;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  background-color: white;
  position: relative;
}

.plan-card::before {
  content: '';
  position: absolute;
  left: 24rpx;
  top: 50%;
  transform: translateY(-50%);
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background-color: $primary-color;
}

.plan-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 48rpx;
  margin-bottom: $spacing-xs;
}

.plan-title {
  font-size: $font-size-base;
  color: $text-primary;
  flex: 1;
}

.plan-status {
  font-size: $font-size-xs;
  padding: 4rpx 16rpx;
  border-radius: 10rpx;
}

.status-in-progress {
  background-color: $primary-color;
  color: white;
}

.status-pending {
  background-color: #f0f0f0;
  color: $text-secondary;
  border: 1rpx solid #d9d9d9;
}

.plan-time {
  font-size: $font-size-sm;
  color: $text-secondary;
  padding-left: 48rpx;
}



/* 卡片悬停效果 */
.card-hover {
  transform: translateY(-4rpx);
  box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}
</style>